import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
// import Login from '@/views/Login.vue'
// import Index from '@/views/Index.vue'
// import Menu from '@/views/menu/Menu.vue'
// import Role from '@/views/role/Role.vue'
// import User from '@/views/user/User.vue'
// import FileUpload from '@/views/file/FileUpload.vue'
// import FileList from '@/views/file/FileList.vue'
// import AlbumCollectionManage from '@/views/albumCollection/albumCollectionManage.vue'
// import AlbumCollectionShow from '@/views/albumCollection/albumCollectionShow.vue'
// import NotifySetting from '@/views/dailyPlan/NotifySetting.vue'
// import FamilyGroupSetting from '@/views/albumCollection/familyGroupSetting.vue'
const Login = defineAsyncComponent(() => import('@/views/Login.vue'))
const Index = defineAsyncComponent(() => import('@/views/Index.vue'))
const DailyPlan = defineAsyncComponent(() => import('@/views/dailyPlan/DailyPlan.vue'))
const DailyTask = defineAsyncComponent(() => import('@/views/dailyPlan/DailyTask.vue'))
const NotifySetting = defineAsyncComponent(() => import('@/views/dailyPlan/NotifySetting.vue'))
const Menu = defineAsyncComponent(() => import('@/views/menu/Menu.vue'))
const Role = defineAsyncComponent(() => import('@/views/role/Role.vue'))
const User = defineAsyncComponent(() => import('@/views/user/User.vue'))
const FileUpload = defineAsyncComponent(() => import('@/views/file/FileUpload.vue'))
const FileList = defineAsyncComponent(() => import('@/views/file/FileList.vue'))
const AlbumCollectionManage = defineAsyncComponent(() => import('@/views/albumCollection/albumCollectionManage.vue'))
const AlbumCollectionShow = defineAsyncComponent(() => import('@/views/albumCollection/albumCollectionShow.vue'))
const FamilyGroupSetting = defineAsyncComponent(() => import('@/views/albumCollection/familyGroupSetting.vue'))
const WeeklyCinema = defineAsyncComponent(() => import('@/views/entertainment/weeklyCinema.vue'))
const Ai = defineAsyncComponent(() => import('@/views/ai/ai.vue'))
const Accounting = defineAsyncComponent(() => import('@/views/accounting/accounting.vue'))
const AccountingSummary = defineAsyncComponent(() => import('@/views/accounting/accountingSummary.vue'))
const OilPrice = defineAsyncComponent(() => import('@/views/oilPrice/oilPrice.vue'))
const DouyinHot = defineAsyncComponent(() => import('@/views/douyinHot/douyinHot.vue'))
import { setToken, getToken, setMenuListStr } from '@/utils/auth';
import { currentUserMenu } from '@/api/user/user';
import { defineAsyncComponent } from 'vue'
import { showErrorMsg } from '@/api/common'
const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    // { path: '/about', name: 'about', component: () => import('../views/AboutView.vue') },
    { path: '/login', name: 'Login', component: Login },
    {
      path: '/',
      name: 'Index',
      component: Index,
      // 嵌套路由；这样定义后，Index.vue里的路由跳转只会在Index.vue内部的<router-view>里显示页面，而不是显示在App.vue里的<router-view>
      children: [
        { path: '/dailyPlan', name: 'dailyPlan', component: DailyPlan, },
        { path: '/dailyTask', name: 'dailyTask', component: DailyTask, },
        { path: '/notifySetting', name: 'notifySetting', component: NotifySetting },
        { path: '/ai', name: 'ai', component: Ai },
        { path: '/menu', name: 'menu', component: Menu },
        { path: '/role', name: 'role', component: Role },
        { path: '/user', name: 'user', component: User },
        { path: '/fileUpload', name: 'fileUpload', component: FileUpload },
        { path: '/fileList', name: 'fileList', component: FileList },
        { path: '/albumCollectionManage', name: 'albumCollectionManage', component: AlbumCollectionManage },
        { path: '/albumCollectionShow', name: 'albumCollectionShow', component: AlbumCollectionShow },
        { path: '/familyGroupSetting', name: 'familyGroupSetting', component: FamilyGroupSetting },
        { path: '/weeklyCinema', name: 'weeklyCinema', component: WeeklyCinema },
        { path: '/accounting', name: 'accounting', component: Accounting },
        { path: '/accountingSummary', name: 'accountingSummary', component: AccountingSummary },
        { path: '/oilPrice', name: 'oilPrice', component: OilPrice },
        { path: '/douyinHot', name: 'douyinHot', component: DouyinHot },
      ],
    },
  ]
})
// 路由守卫; 每一次页面跳转都会走这里判断。
router.beforeEach((to, from, next) => {
  const invalidCallback = to.query['Z-WX_LOGIN_INVALID_CALLBACK'] as string | undefined;
  if (invalidCallback) {
    next({ name: 'Login' });
    showErrorMsg("无效的扫码回调，请重新登录！");
    return;
  }
  const wxLoginExpire = to.query['WX_LOGIN_EXPIRE'] as string | undefined;
  if (wxLoginExpire) {
    next({ name: 'Login' });
    showErrorMsg("扫码超时，请重新扫码！");
    return;
  }
  const zToken = to.query['Z-Token'] as string | undefined;
  let loggedIn = false;
  if (zToken) {
    // 在这里处理 Z-Token，例如验证它或将其存储在状态管理中
    setToken(zToken);
    loggedIn = true;
    currentUserMenu().then((res) => {
      if (res.status != 200) {
        showErrorMsg(res.msg);
      } else {
        setMenuListStr(res.data);
        if (to.name !== 'Login' && !loggedIn) {
          // 如果需要登录但用户未登录，则重定向到登录页面
          next({ name: 'Login' });
        } else if (to.name === 'Login' && loggedIn) {
          // 如果用户已经登录，并且尝试访问登录页面，则重定向到首页
          next({ name: 'Index' });
        } else {
          // 否则继续到目标路由
          next();
        }
      }
    })
  } else {
    if (getToken()) {
      loggedIn = true;
    }
    // 原逻辑原理：
    // 未登录 + 访问非login  -> 改为访问login
    // 未登录 + 访问login    -> 走最终的next()
    // 已登录 + 访问login    -> 改为访问index
    // 已登录 + 访问非login  -> 走最终的next()
    // 一定注意最后的else里的next()是关键，你会发现你改了路由，最终都会进这个next()。

    // if (to.name !== 'Login' && !loggedIn) {
    //   // 如果需要登录但用户未登录，则重定向到登录页面
    //   next({ name: 'Login' });
    //   console.log('login...');
    // }
    // else if (to.name === 'Login' && loggedIn) {
    //   // 如果用户已经登录，并且尝试访问登录页面，则重定向到首页
    //   next({ name: 'Index' });
    // } else {
    //   // 否则继续到目标路由
    //   next();
    // }


    // 修改背景：新逻辑，试用角色过期时，如果本地有token，那么会直接进首页，还有试用角色，这里需要再次获取菜单
    // 新逻辑里，相当于：未登录不用动；已登录状态下多一个查询当前人员菜单权限的动作。
    if (to.name !== 'Login' && !loggedIn) {
      // 如果需要登录但用户未登录，则重定向到登录页面
      next({ name: 'Login' });
    } else if (to.name === 'Login' && loggedIn) {
      // 如果用户已经登录，并且尝试访问登录页面，则重定向到首页
      next({ name: 'Index' });
    } else {
      if (!loggedIn) {
        // 否则继续到目标路由
        next();
      } else {
        currentUserMenu().then((res) => {
          if (res.status != 200) {
            showErrorMsg(res.msg);
          } else {
            setMenuListStr(res.data);
            next();
          }
        })
      }
    }
  }
});

export default router
